package process

import (
	log "github.com/cihub/seelog"
	"matching/conf"
	"matching/engine"
	"matching/enum"
	"matching/jobline"
	"matching/middleware"
	"matching/middleware/cache"
	"matching/middleware/mq"
	"matching/utils"
)

// 这里将做一些初始化操作

// 1.载入配置，启动日志、2.链接redis、3.链接mq、4.读取交易对开启交易引擎   5.载入交易订单  6.载入交易撤单
func Init()  {
	conf.Init()
	log.Infof("config load success!")
	middleware.Init()
	mq.Init()
	engine.Init()
	symbols:=cache.GetSymbols()
	for _,value:=range symbols{
		price:=cache.GetLastPrice(value)
		info:=cache.GetSymbolInfo(value)
		errcode:=CreateEngine(value,utils.StringToDecimal(price),info.CoinScale,info.BaseCoinScale)
		log.Infof("create %s engine ,price %s is create code=%s",value,price,errcode)
	}
	log.Infof("...loading create orders...start ....")

	for _,value:=range symbols{
		orderIds:=cache.RangeOrderSort(value,enum.ActionCreate)
		//检查订单是否已交易完成（非撤单状态、剩余交易量小于总交易量、交易中状态）
		num:=0
		for _,orderId:=range orderIds{
			order:=cache.GetOrderObject(orderId,value)
			if order.OrderId=="" || order.Status!=enum.TREADING {
				//订单不存在或者已撤单或已完成成交等非交易中状态
				cache.DeleteOrderSortOne(value,enum.ActionCreate,orderId)
			}else {
				//加入撮合引擎
				num++
				engine.ChanMap[order.Symbol] <- order
			}
		}
		log.Infof("symbol : %s ,init add order %d",value,num)
	}
	log.Infof("...loading create orders...end ....")

	//重载撤单请求
	log.Infof("...loading cancel orders...start ....")

	for _,value:=range symbols{
		orderIds:=cache.RangeOrderSort(value,enum.ActionCancel)
		//检查订单是否已交易完成（非撤单状态）
		num:=0
		for _,orderId:=range orderIds{
			order:=cache.GetOrderObject(orderId,value)
			if order.OrderId=="" || order.Status==enum.CANCELED {
				//订单不存在或者已撤单
				cache.DeleteOrderSortOne(value,enum.ActionCancel,orderId)
			}else {
				//置为撤单需求，加入撮合引擎
				order.Action=enum.ActionCancel
				num++
				engine.ChanMap[order.Symbol] <- order
			}
		}
		log.Infof("symbol : %s ,init cancel order %d",value,num)
	}
	jobline.Init()
}